const express = require('express');
const router = express.Router();
const { Article, User } = require('../../models');
const { success, failure } = require('../../utils/responses');
const { NotFound } = require('http-errors');

/**
 * 公共方法：关联用户数据
 * @returns {{include: [{as: string, model, attributes: string[]}], attributes: {exclude: string[]}}}
 */
const getCondition = () => {
  return {
    attributes: { exclude: ['UserId'] },
    include: [
      {
        model: User,
        as: 'user',
        attributes: ['id', 'username', 'avatar'],
      },
    ],
  };
};

/**
 * 查询文章列表
 * GET /web/articles
 */
router.get('/', async (req, res) => {
  try {
    const query = req.query;
    const currentPage = Math.abs(Number(query.currentPage)) || 1;
    const limit = Math.abs(Number(query.pageSize)) || 10;
    const offset = (currentPage - 1) * limit;

    const condition = {
      ...getCondition(),
      order: [['id', 'DESC']],
      limit,
      offset,
      where: {},
    };
    if (query.title) {
      condition.where.title = {
        [Op.like]: `%${query.title}%`,
      };
    }
    if (query.status) {
      condition.where.status = query.status;
    }
    if (query.userId) {
      condition.where.userId = query.userId;
    }

    const { count, rows } = await Article.findAndCountAll(condition);
    success(res, '查询文章列表成功。', {
      data: rows,
      total: count,
    });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 查询文章详情
 * GET /web/articles/:id
 */
router.get('/:id', async (req, res) => {
  try {
    const id = req.params.id;
    
    const article = await Article.findByPk(id, getCondition());
    if (!article) {
      throw new NotFound('文章不存在。');
    }
    success(res, '查询文章详情成功。', article);
  } catch (error) {
    failure(res, error);
  }
});
module.exports = router;
